import { ApiCall } from 'tsrpc'
import { ReqGetConfigSchemas, ResGetConfigSchemas, ConfigSchemaInfo } from '../shared/api_config_editor/PtlGetConfigSchemas'

// 导入Schema定义
import { EquipmentConfigSchema, SkillConfigSchema, PropConfigSchema } from '../config/metadata/ConfigSchema'

export default async function (call: ApiCall<ReqGetConfigSchemas, ResGetConfigSchemas>) {
    try {
        // 构建Schema信息列表
        const schemaInfos: ConfigSchemaInfo[] = []
        
        // 内置Schema
        const builtinSchemas = [
            EquipmentConfigSchema,
            SkillConfigSchema,
            PropConfigSchema
        ]
        
        for (const schema of builtinSchemas) {
            schemaInfos.push({
                version: schema.version,
                type: schema.type,
                name: schema.name,
                description: schema.description,
                fieldCount: schema.fields.length,
                groupCount: schema.groups?.length || 0,
                lastModified: Date.now() // 内置Schema使用当前时间
            })
        }
        
        // 检查是否有自定义Schema文件
        const fs = require('fs')
        const path = require('path')
        const schemaDir = path.resolve(__dirname, '../config/schemas')
        
        if (fs.existsSync(schemaDir)) {
            try {
                const files = fs.readdirSync(schemaDir)
                const schemaFiles = files.filter((file: string) => file.endsWith('.json'))
                
                for (const file of schemaFiles) {
                    try {
                        const filePath = path.join(schemaDir, file)
                        const content = fs.readFileSync(filePath, 'utf-8')
                        const schema = JSON.parse(content)
                        
                        // 验证Schema基本结构
                        if (schema.type && schema.name && schema.fields && Array.isArray(schema.fields)) {
                            const stats = fs.statSync(filePath)
                            
                            schemaInfos.push({
                                version: schema.version || '1.0.0',
                                type: schema.type,
                                name: schema.name,
                                description: schema.description || '',
                                fieldCount: schema.fields.length,
                                groupCount: schema.groups?.length || 0,
                                lastModified: stats.mtime.getTime()
                            })
                        }
                    } catch (error) {
                        console.warn(`Failed to read schema file ${file}:`, error)
                    }
                }
            } catch (error) {
                console.warn('Failed to read schema directory:', error)
            }
        }
        
        // 按类型排序
        schemaInfos.sort((a, b) => a.type.localeCompare(b.type))
        
        call.succ({
            data: schemaInfos
        })
        
    } catch (error) {
        console.error('Failed to get config schemas:', error)
        call.error('获取配置Schema失败', {
            errors: [(error as any).message]
        })
    }
}
